import { PrismaClient } from '@prisma/client'
import { readBody } from 'h3'
const prisma = new PrismaClient()

export default defineEventHandler(async (event) => {
    const { topic } = await readBody(event)
    // 查询考试信息
    const topicRes = await prisma.topic.findUnique({ where: {id: parseInt(topic) }})
    if(!topicRes) return []
    // 查询所有试题标识，用于随机取出
    const res = await prisma.options.findMany({
        where: { topicId: parseInt(topic) },
        select: { id: true }
    })
    // 随机抽题
    let ids = res.map(({ id }) => id)
    ids = getRandomFromArray(ids, topicRes.quantity)
    const result = await prisma.options.findMany({
        where: {
            id: {
                in: ids
            }
        }
    })
    return {topic: topicRes, options: result}
})


function getRandomFromArray(arr, count) {
    const uniqueValues = new Set();

    // 循环直到达到指定的数量
    while (uniqueValues.size < count) {
        const randomIndex = Math.floor(Math.random() * arr.length);
        uniqueValues.add(arr[randomIndex]);
    }

    return Array.from(uniqueValues); // 转换为数组形式返回
}